import React, { useState, useEffect } from 'react';
import { Progress } from 'antd';
import type { ProgressProps } from 'antd';

import { random } from 'lodash';

import './index.less';

const LoginProgress: React.FC<ILoginProgressProps> = (props) => {
  const [percent, setPercent] = useState<number>(0);

  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;
    const clearTimer = () => {
      if (timer) {
        clearInterval(timer);
      }
    };

    if (props.start && !props.end) {
      setPercent(0);
      timer = setInterval(() => {
        setPercent((prev) => {
          if (prev >= 100) {
            clearInterval(timer!);
            return 100;
          }
          if (10 > prev) {
            return prev + random(0, 3);
          }
          if (15 < prev) {
            return prev + random(0, 8);
          }
          if (90 > prev) {
            return prev + random(0, 3);
          }
        });
      }, 1000);
    }

    if (props.end && !props.start) {
      setPercent(100);
      clearTimer();
    }

    if (props.status && props.status === 'exception') {
      clearTimer();
      setPercent(percent);
    }

    return () => {
      clearTimer();
    };
  }, [props.start, props.end, props.status]);

  return (
    <div className="login-progress">
      <Progress type="circle" percent={percent} width={80} status={props.status} />
      <div className="tips">
        {props.status === 'exception' && '登录失败'}
        {props.status !== 'exception' && percent < 100 && '正在努力登录中，请稍后...'}
        {props.status !== 'exception' && percent === 100 && '登录成功'}
      </div>
    </div>
  );
};

interface ILoginProgressProps {
  start: boolean;
  end: boolean;
  status: ProgressProps['status'];
}

export default LoginProgress;
